package HtServer.meeting;




import HtServer.FileUpload.ImportMeetingFromExcel.ImportMeetingMenber;
import HtServer.RedisTools.RedisToos;
import HtServer.returnObject.ReturnObject;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.params.ScanParams;
import redis.clients.jedis.resps.ScanResult;
import tools.Tools;


import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.*;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Callable;


public class MeetingItems {
    //单例模式
    private static MeetingItems instance = null;
    int currentindex = -1;
    LinkedList<MeetingItem> ll = new LinkedList<MeetingItem>();

    private MeetingItems() {

    }

    public static MeetingItems getInstance() {
        if (instance == null) {
            instance = new MeetingItems();
            instance.getMeetingItemFromRedis();
            getInstance().sort();


        }
        return instance;
    }


    public MeetingItem getCurrentItem() {
        if (currentindex == -1)
            currentindex = 0;
        return this.ll.get(currentindex);

    }
        //获得第一个
    public MeetingItem getFirstItem() {
        currentindex = 0;
        return this.ll.get(currentindex);
    }
    //获得前一个
    public MeetingItem getPreItem() {
        if (currentindex > 0)
            currentindex--;
        else
            currentindex = 0;
        return getCurrentItem();
    }

    //获得后一个,但是光标不移动，
    public MeetingItem getNextItemNotGo() {

        if (currentindex >= this.ll.size() - 1) {
            return null;
        }

        return this.ll.get(currentindex + 1);

    }

    //获得后一个
    public MeetingItem getNextItem() {

        if (currentindex >= this.ll.size() - 1) {
            return null;
        }

        return this.ll.get(++currentindex);

    }

    public void addItem(MeetingItem mi) {
        if (!ll.contains(mi)) {
            ll.add(mi);
        }

    }

    public void remove(MeetingItem mi) {
        if (ll.contains(mi))
            ll.remove(mi);

    }


    //redis 删除某个键
    public void delMeetingItem(String id) {

        MeetingItem mi = getMeetingItem(id);
        if (mi != null) {
            ll.remove(mi);


        }
        Jedis jedis = RedisToos.getInstance().getJedis();
        jedis.del("meetingitem:" + id);
    }

    public MeetingItem getMeetingItem(String id) {
        long T1 = System.currentTimeMillis();
        for (MeetingItem mi : ll) {
            if (mi.id.equals(id))
                return mi;
        }
        long T2 = System.currentTimeMillis();
        System.out.println("getMeetingItem time = " + (T2 - T1) / 1000);

        return null;

    }

    /**
     * 根据lingyu 获得MeetingItem
     * @return
     */
    public LinkedList<MeetingItem> getMeetingItemByLingyu(String lingyu) {
        LinkedList<MeetingItem> ll2 = new LinkedList<>();
        for (MeetingItem mi : ll) {
            if (mi.getLingyu().equals(lingyu))
                ll2.add(mi);
        }
        return ll2;
    }

    /**
     * 根据领域，随机产生num个人员
     */
    public List getMeetingItemByLingyuRandom(String lingyu, int num) {
        LinkedList<MeetingItem> ll2 = getMeetingItemByLingyu(lingyu);
        //过滤掉ll2 内容10个字的以内的
        for (MeetingItem mi : ll2) {
            if (mi.getContents().length() < 10) {
                ll2.remove(mi);
            }
        }
        return Tools.Random(ll2, num);
    }




    /**
     * 全领域进行随机，每个领域随机不同的数量
     */
    public List getMeetingItemByLingyuRandom() {
        HashMap hashMap = getMeetingItemByLingyu();
        List list = new LinkedList();
        for (Object key : hashMap.keySet()) {
            LinkedList<MeetingItem> ll2 = (LinkedList<MeetingItem>) hashMap.get(key);
            //过滤掉ll2 内容10个字的以内的
            for (MeetingItem mi : ll2) {
                if (mi.getContents().length() < 10) {
                    ll2.remove(mi);
                }
            }
            int num;
            try {
                 num = ll2.get(0).getRandomnum();
            }
            catch (Exception e)
            {
                System.out.println("error in getMeetingItemByLingyuRandom" + e.getMessage());
                 num = 3;
            }
            list.addAll(Tools.Random(ll2, num));
        }
        return list;
    }

    /**
     * 根据领域进行分组，放在hashmap 里
     * 内容为空或者内容少于10个字不返回
     * @return
     */
    public HashMap getMeetingItemByLingyu() {
        HashMap hashMap = new HashMap();
        for (MeetingItem mi : ll) {
            //没有内容的就不要啥会跟你去发言了
            if (mi.getContents()!=null && mi.getContents().length()>10) {
                if (!hashMap.containsKey(mi.getLingyu())) {


                    LinkedList<MeetingItem> ll2 = new LinkedList<>();
                    ll2.add(mi);
                    hashMap.put(mi.getLingyu(), ll2);

                } else {
                    LinkedList<MeetingItem> ll2 = (LinkedList<MeetingItem>) hashMap.get(mi.getLingyu());
                    ll2.add(mi);
                }
            }
        }
        return hashMap;
    }



    public JSONArray getAllItems() {
        JSONArray jsonArray = new JSONArray();
        for (MeetingItem mi : ll) {

            JSONObject obj = new JSONObject();
            obj.put("label", mi.getName());
            obj.put("value", mi.getId());
            jsonArray.add(obj);

        }
        return jsonArray;
    }


    public static  String _radonBase64() {
        //随机产生base64 的图片
        BufferedImage image = new BufferedImage(30, 30, BufferedImage.TYPE_INT_RGB);

        // 使用随机颜色填充图片
        Random rand = new Random();
        for (int x = 0; x < 30; x++) {
            for (int y = 0; y < 30; y++) {
                int red = rand.nextInt(256);
                int green = rand.nextInt(256);
                int blue = rand.nextInt(256);
                Color color = new Color(red, green, blue);
                image.setRGB(x, y, color.getRGB());
            }
        }

        // 将图片转换为Base64编码的字符串
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "png", outputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        byte[] imageBytes = outputStream.toByteArray();
        String base64Image = Base64.getEncoder().encodeToString(imageBytes);

//        return "data:image/png;base64,"+base64Image;
        return base64Image;
    }



    //从redis 获取 MeetingItem
    public void getMeetingItemFromRedis()
    {
        ll.clear();
        Jedis jedis = RedisToos.getInstance().getJedis();
        String cursor = "0";
        ScanParams scanParams = new ScanParams().match("meetingitem:*");
        do {
            ScanResult<String> scanResult =  jedis.scan(cursor, scanParams);
            List<String> keys = scanResult.getResult();


            for (String key : keys) {
                String userData = jedis.get(key);
//                System.out.println("Key: " + key + ", Data: " + userData);
                MeetingItem mi = JSON.parseObject(userData, MeetingItem.class);
//                System.out.println("MeetingItem: " + mi);

                instance.addItem(mi);

            }

            cursor = scanResult.getCursor();
        } while (!cursor.equals("0"));


    }


    /**
     *
     * @param totaltime 总时间 秒
     * @param intervaltime 间隔时间 秒
     * @return
     */
    //从redis 立获得MeetingItem内容的播报时间
    //记录条数*2000ms+字数*滚动速度（ms） = 总体播放时间（S）
    public int getMeetingItemTimeFromRedis(int totaltime,int intervaltime ) {

        int wordcount = 0;
        for (MeetingItem mi:MeetingItems.getInstance().ll)
        {
//            System.out.println(mi.getContents());
            wordcount += mi.getContents()==null?0:mi.getContents().length();
        }


        return (totaltime*1000-ll.size()*intervaltime*1000)/wordcount;


    }

    /**
     * redis 中获得所有小组名称
     *
     */
    public HashMap getGroupNames() {
        Jedis jedis = RedisToos.getInstance().getJedis();
        String cursor = "0";
        ScanParams scanParams = new ScanParams().match("meetingitem:*");

        HashMap hashMap = new HashMap();
        do {
            ScanResult<String> scanResult = jedis.scan(cursor, scanParams);
            List<String> keys = scanResult.getResult();

            for (String key : keys) {
                String userData = jedis.get(key);

                MeetingItem mi = JSON.parseObject(userData, MeetingItem.class);



                if(!hashMap.containsKey(mi.getGroupid()))
                {

                    hashMap.put(mi.getGroupid(),mi.getGroupname());
                }


            }
            cursor = scanResult.getCursor();
        }
        while (!cursor.equals("0"));

        return hashMap;
    }
    /**
     * 根据个人点赞数量排名，返回前10
     */
    public Vector<MeetingItem> getTopLike(int num)
    {
        Jedis jedis = RedisToos.getInstance().getJedis();
        String cursor = "0";
        ScanParams scanParams = new ScanParams().match("meetingitem:*");

        HashMap hashMap = new HashMap();
        do {
            ScanResult<String> scanResult = jedis.scan(cursor, scanParams);
            List<String> keys = scanResult.getResult();

            for (String key : keys) {
                try {
                String userData = jedis.get(key);


                    MeetingItem mi = JSON.parseObject(userData, MeetingItem.class);


                    hashMap.put(mi.getName(), mi.getLike());
                } catch (Exception e) {
//                    System.err.println(userData);

                    System.err.println("error in getTopLike" + e.getMessage());
                }

            }
            cursor = scanResult.getCursor();
        } while (!cursor.equals("0"));

        Vector<MeetingItem> V = new Vector<>();
        for (Object key : hashMap.keySet()) {
            MeetingItem mi = new MeetingItem();
            mi.setName((String) key);
            mi.setLike((int) hashMap.get(key));
            V.add(mi);
        }
        //根据like 数量排序
        Collections.sort(V, new Comparator<MeetingItem>() {
            @Override
            public int compare(MeetingItem o1, MeetingItem o2) {
                int like = o2.getLike() - o1.getLike();
                return like;
            }
        });

//        Collections.sort(V);
        Vector<MeetingItem> V2 = new Vector<>();
        for (int i = 0; i < num; i++) {
            if (V.size()>i)
            {
                V2.add(V.get(i));
            }

        }
        return V2;
    }


    public JSONObject getTopLikeJSON(int num)
    {
        Vector<MeetingItem> V2 = new Vector<>();
        V2 = getTopLike(num);
        String xAxis = "";
        String yAxis = "";
        for (MeetingItem mi:V2)
        {
            xAxis += mi.getName()+",";
            yAxis += mi.getLike()+",";
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("xAxis",xAxis);
        jsonObject.put("yAxis",yAxis);
        return jsonObject;


    }
    /**
     * 根据小组名称汇总点赞数量
     *
     */

    public HashMap getGroupLikeCount() {
        Jedis jedis = RedisToos.getInstance().getJedis();
        String cursor = "0";
        ScanParams scanParams = new ScanParams().match("meetingitem:*");

        HashMap hashMap = new HashMap();
        do {
            ScanResult<String> scanResult = jedis.scan(cursor, scanParams);
            List<String> keys = scanResult.getResult();

            for (String key : keys) {
                String userData = jedis.get(key);

                MeetingItem mi = JSON.parseObject(userData, MeetingItem.class);

                if (!hashMap.containsKey(mi.getGroupname())) {
                    hashMap.put(mi.getGroupname(), mi.getLike());
                } else {
                    int like = (int) hashMap.get(mi.getGroupname());
                    hashMap.put(mi.getGroupname(), like + mi.getLike());
                }
            }
            cursor = scanResult.getCursor();
        } while (!cursor.equals("0"));

        return hashMap;
    }

    /**
     * 根据组id获得小组成员
     */
    public Vector<MeetingItem> getGroupMembers(String groupid)
    {
        Jedis jedis = RedisToos.getInstance().getJedis();
        Vector<MeetingItem> V = new Vector<>();
        String cursor = "0";
        ScanParams scanParams = new ScanParams().match("meetingitem:*");
        do {
            ScanResult<String> scanResult = jedis.scan(cursor, scanParams);
            List<String> keys = scanResult.getResult();


            for (String key : keys) {
                String userData = jedis.get(key);
//                System.out.println("Key: " + key + ", Data: " + userData);
                MeetingItem mi = JSON.parseObject(userData, MeetingItem.class);
//                System.out.println("MeetingItem: " + mi);

                if(groupid==null)
                {
                    V.add(mi);
                }
                else if(mi.getGroupid().equals(groupid))
                {
                    V.add(mi);
                }


            }

            cursor = scanResult.getCursor();
        } while (!cursor.equals("0"));
        Collections.sort(V);
        return V;
    }


    public void sort()
    {
        Collections.sort(ll);
    }

    public LinkedList<MeetingItem> getLl() {
        return ll;
    }

    public void setLl(LinkedList<MeetingItem> ll) {
        this.ll = ll;
    }

    public static void main(String[] argc) throws IOException {


        ImportMeetingMenber importMeetingMenber1 = new ImportMeetingMenber("/Users/zgw/temp/writelingyu.xlsx");

        importMeetingMenber1.MeetingMenberImages();
        importMeetingMenber1.ImportMeetingMenberCells();
        importMeetingMenber1.meetingItems.forEach(System.out::println);
        importMeetingMenber1.write2Rides();

        MeetingItems.getInstance().getMeetingItemFromRedis();
        MeetingItems.getInstance().sort();

//        MeetingItems.getInstance().delMeetingItem("e159a9c0-4c89-499f-8071-fbc819d5b7b5");
//        System.out.println(MeetingItems.getInstance().ll);


//        int wordcount = 0;
//        for (MeetingItem mi:MeetingItems.getInstance().ll)
//        {
////            System.out.println(mi.getContents());
//            wordcount += mi.getContents().length();
//        }
//        System.out.println("wordcount = "+wordcount);

//        System.out.println(MeetingItems.getInstance().getMeetingItemTimeFromRedis(1800,2));


//        System.out.println(MeetingItems.getInstance().getGroupMembers("2"));
//        System.out.println(MeetingItems.getInstance().getGroupNames());
//        Vector v = MeetingItems.getInstance().getGroupMembers("2");
//        System.out.println(JSON.toJSON(v));
//        System.out.println(JSON.toJSON(MeetingItems.getInstance().getGroupNames()));


//        System.out.println(MeetingItems.getInstance().getGroupLikeCount());
//        System.out.println(MeetingItems.getInstance().getTopLike(20));
//        System.out.println(JSON.toJSON(MeetingItems.getInstance().getTopLike(20)));
//        System.out.println(MeetingItems.getInstance().getTopLikeJSON(20));
       System.out.println("区分领域");
        HashMap hashMap = MeetingItems.getInstance().getMeetingItemByLingyu();
        System.out.println(JSON.toJSONString(hashMap));
        for (Object key : hashMap.keySet()) {
            System.out.println(key);
            System.out.println(hashMap.get(key));
        }


       LinkedList linkedList =  MeetingItems.getInstance().getMeetingItemByLingyu("生产领域");
        System.out.println(JSON.toJSONString(linkedList));



        List list =  Tools.Random(linkedList, 3);
        System.out.println(JSON.toJSONString(list));

        System.out.println("全领域");
        List list2 = MeetingItems.getInstance().getMeetingItemByLingyuRandom();
        System.out.println(JSON.toJSONString(list2));


    }



}

